package com.bzoa.api.config;

import com.springboot.common.entity.ResponseResult;
import com.springboot.common.entity.ResponseStatus;
import com.springboot.common.util.JsonUtil;
import com.springboot.common.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
/**
 * 创建者: lands
 * 创建时间:2023/3/3 0:56
 *  登录拦截
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        response.setContentType("application/json;charset=utf-8");
        //从 http 请求头中取出 token
        String token = request.getHeader("token");

        if (token == null) {
            PrintWriter out = response.getWriter();
            out.print(JsonUtil.toJsonString(ResponseResult.error(ResponseStatus.LOGIN_INFO)));
            return false;
        }
        //验证 token
        if(JwtUtils.checkToken(token)){
            return true;
        }else {
            PrintWriter out = response.getWriter();
            out.print(JsonUtil.toJsonString(ResponseResult.error(ResponseStatus.LOGIN_TIME_OUT)));
            return false;
        }


    }
}

